<?php
declare(strict_types=1);

namespace app\api\controller\admin;

use app\common\model\Area;
use app\common\model\delivery\CardLog;
use app\common\model\delivery\Channel;
use app\common\model\delivery\ChannelGird;
use app\common\model\delivery\ChannelOrder;
use app\common\model\delivery\CouponList;
use app\common\model\delivery\Customer as CustomerModel;
use app\common\model\delivery\CustomerAddress;
use app\common\model\delivery\CustomerGoods;
use app\common\model\delivery\MonthBill;
use app\common\model\delivery\PayLog;
use app\common\model\UserLog;
use app\common\service\msg\WechatMsg;
use think\annotation\route\Get;
use think\annotation\route\Group;
use think\annotation\route\Post;
use think\facade\Db;

#[Group("admin/customer")]
class Customer extends Base {

    #[Get('list')]
    public function list()
    {
        $page=$this->request->get('page/d',1);
        $offest=($page-1)*15;
        $list=CustomerModel::withJoin(['area'],'left')->where(function ($query){
            $keywords=$this->request->get('keywords');
            $type=$this->request->get('type');
            $query->where('customer_type',$type);
            if($this->seller){
                $query->where(['customer.channel_id'=>$this->channel->id,'customer.seller_id'=>$this->seller->id]);
            }else{
                $query->where(['customer.channel_id'=>$this->channel->id]);
            }
            if($keywords){
                $query->whereRaw("customer.name like '%{$keywords}%' or customer.address like '%{$keywords}%' or customer.contact like '%{$keywords}%'");
            }
        })->limit($offest,15)->order('customer.id desc')->select();
        $this->success('',$list);
    }

    #[Post('updatecover')]
    public function updatecover()
    {
        $id=$this->request->post('id');
        $url=$this->request->post('url');
        CustomerModel::where(['id'=>$id])->update(['cover_url'=>$url]);
        $this->success();
    }

    #[Get('getChannel')]
    public function getChannel()
    {
        $channel=$this->channel;
        $seller=$this->seller;
        $settle_type=Channel::SETTLE_TYPE;
        $gird=ChannelGird::where(['channel_id'=>$channel->id])->select();
        $this->success('',compact('channel','seller','settle_type','gird'));
    }

    #[Get('getCustomer')]
    public function getCustomer()
    {
        $id=$this->request->get('customer_id');
        $channel=$this->channel;
        $seller=$this->seller;
        $customer=CustomerModel::find($id);
        if($customer->channel_id!= $this->channel->id){
            $this->error('无权限操作');
        }
        if($this->seller && $customer->seller_id!=$this->seller->id){
            $this->error('无权限操作');
        }
        $customer->goods=CustomerModel::parseGoods($customer->goods,$channel);
        $settle_type=Channel::SETTLE_TYPE;
        $gird=ChannelGird::where(['channel_id'=>$channel->id])->select();
        $this->success('',compact('customer','channel','seller','settle_type','gird'));
    }

    #[Get('orderlist')]
    public function orderlist()
    {
        $page=$this->request->get('page/d',1);
        $offest=($page-1)*10;
        $list1=ChannelOrder::withJoin(['customer','goods','spec'],'left')->where(function ($query){
            $query->where('channel_order.channel_id','=',$this->channel->id);
            $query->where('channel_order.is_cancel','=',0);
            $query->whereRaw("channel_order.is_pay=1 or (channel_order.pay_type='delivery' and channel_order.is_pay=0)");
            $customer_id=$this->request->get('customer_id');
            if($customer_id){
                $query->where('channel_order.customer_id','=',$customer_id);
            }
            $date=$this->request->get('date');
            $end=strtotime(date('Y-m-d 23:59:59',time()));
            if($date==1){
                $start=$end-60*24*3600;
                $query->whereBetween('channel_order.createtime',[$start,$end]);
            }
            if($date==2){
                $start=$end-30*24*3600;
                $query->whereBetween('channel_order.createtime',[$start,$end]);
            }
            if($date==3){
                $start=$end-15*24*3600;
                $query->whereBetween('channel_order.createtime',[$start,$end]);
            }
        })->limit($offest,10)->order('id desc')->select()->toArray();
        foreach ($list1 as $key=>$value){
            $list1[$key]['pay_type']=ChannelOrder::PAY_TYPE[$value['pay_type']];
        }
        $this->success('',$list1);
    }

    #[Post('edit')]
    public function edit()
    {
        $info=$this->request->post();
        $customerGoods=[];
        foreach ($info['goods'] as $goods){
            foreach ($goods['spec'] as $spec){
                $customerGoods[]=[
                    'goods_id'=>$goods['id'],
                    'spec_id'=>$spec['id'],
                    'price'=>$spec['price'],
                ];
            }
        }
        if($info['id']){
            $customer=CustomerModel::find($info['id']);
            if($customer->channel_id!= $this->channel->id){
                $this->error('无权限操作');
            }
            if($this->seller && $customer->seller_id!=$this->seller->id){
                $this->error('无权限操作');
            }
        }else{
            $customer=new CustomerModel();
        }
        $customerinfo=[
            'id'=>$info['id'],
            'customer_type'=>$info['customer_type'],
            'channel_id'=>$this->channel->id,
            'seller_id'=>$this->seller?$this->seller->id:null,
            'user_id'=>$info['user_id'],
            'name'=>$info['name'],
            'cover_url'=>(count($info['cover_url'])>0)?$info['cover_url'][0]['url']:'',
            'license'=>$info['license'],
            'license_photo'=>(count($info['license_photo'])>0)?$info['license_photo'][0]['url']:'',
            'province_id'=>$info['region'][0],
            'city_id'=>$info['region'][1],
            'area_id'=>$info['region'][2],
            'gird_id'=>isset($info['gird_id'])?$info['gird_id']:null,
            'address'=>$info['address'],
            'latitude'=>$info['latitude'],
            'longitude'=>$info['longitude'],
            'contact'=>$info['contact'],
            'mobile'=>$info['mobile'],
            'settle_type'=>$info['settle_type'],
            'bill_date'=>$info['bill_date'],
            'status'=>'normal',
            'updatetime'=>time(),
        ];
        $err='';
        Db::startTrans();
        try {
            $customer->save($customerinfo);
            CustomerGoods::where(['customer_id' => $customer->id])->delete();
            foreach ($customerGoods as $k => $v) {
                $customerGoods[$k]['customer_id'] = $customer->id;
            }
            (new CustomerGoods())->saveAll($customerGoods);
            $mergename=Area::find($info['region'][2])->mergename;
            $addressinfo=[
                'customer_id'=>$customer->id,
                'province_id'=>$info['region'][0],
                'city_id'=>$info['region'][1],
                'area_id'=>$info['region'][2],
                'mergename'=>$mergename,
                'detail'=>$info['address'],
                'longitude'=>$info['longitude'],
                'latitude'=>$info['latitude'],
                'info'=>json_encode([
                    'title'=>$mergename,
                    'address'=>$info['address']
                ],JSON_UNESCAPED_UNICODE),
                'contact'=>$info['contact'],
                'mobile'=>$info['mobile'],
                'sex'=>1,
                'is_default'=>1
            ];
            if($info['id']){
                CustomerAddress::where(['customer_id'=>$customer->id,'is_default'=>1])->update($addressinfo);
            }else{
                (new CustomerAddress())->save($addressinfo);
            }
            Db::commit();
        }catch (\Exception $e){
            $err=$e->getMessage();
            Db::rollback();
        }
        if($err){
            $this->error('操作失败：'.$err);
        }
        if(!$info['id']){
            WechatMsg::addCustomerNoticeToUser($customer);
        }
        $this->success('操作成功');
    }

    #[Get('yuefubill')]
    public function yuefubill()
    {
        $page=$this->request->get('page');
        $offset=($page-1)*15;
        $list=MonthBill::withJoin(['customer','goods'],'inner')->where(function ($query){
            $query->where('month_bill.is_pay','=',0);
            $keywords=$this->request->get('keywords');
            if($keywords){
                $query->where('customer.name','like','%'.$keywords.'%');
            }
        })->limit($offset,15)->order('id desc')->select();
        $this->success('',$list);
    }

    #[Post('noticePay')]
    public function noticePay()
    {
        $ids=$this->request->post('ids');
        $list=MonthBill::withJoin(['customer','goods'],'inner')->where('month_bill.id','in',$ids)->select();
        foreach ($list as $item){
            $users=explode(',',$item->customer->user_id);
            foreach ($users as $user_id){
                WechatMsg::noticePayMonthBill($user_id,$item);
            }
        }
        $this->success('通知成功');
    }

    #[Post('paymonth')]
    public function paymonth()
    {
        $postdata=$this->request->post();
        $bill=MonthBill::find($postdata['id']);
        if($bill->is_pay==1){
            $this->error('账单已支付');
        }
        $starttime=strtotime($bill->starttime);
        $endtime=strtotime($bill->endtime);
        $total_money=ChannelOrder::where(['customer_id'=>$bill->customer_id,'goods_id'=>$bill->goods_id,'is_cancel'=>0,'pay_type'=>'month','pay_id'=>null])->where('createtime','between',[$starttime,$endtime])->sum('total_money');
        if($total_money!=$bill->total_money){
            $this->error('账单金额不正确');
        }
        Db::startTrans();
        try{
            $orderNo=create_out_trade_no();
            $log=new PayLog();
            $log->save([
                'user_id'=>$this->auth->id,
                'type'=>PayLog::TYPE('支付月付账单'),
                'pay_price'=>$bill->total_money,
                'out_trade_no'=>$orderNo,
                'pay_status'=>1,
                'pay_time'=>date('Y-m-d H:i:s',time())
            ]);
            $bill->order_no=$orderNo;
            $bill->is_pay=1;
            $bill->pay_id=$log->id;
            $bill->remark='线下支付-'.$postdata['remark'];
            $bill->save();
            ChannelOrder::where(['customer_id'=>$bill->customer_id,'goods_id'=>$bill->goods_id,'is_cancel'=>0,'pay_type'=>'month','pay_id'=>null])->where('createtime','between',[$starttime,$endtime])->update(['pay_id'=>$log->id]);
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付成功');
    }

    #[Get('card')]
    public function card()
    {

        $page=$this->request->get('page/d',1);
        $offest=($page-1)*15;
        $list=CouponList::withJoin(['coupon','customer'],'inner')->where(function($query){
            $type=$this->request->get('type');
            $query->where('coupon_list.channel_id','=',$this->channel->id);
            $query->where('coupon.type','=',$type);
            $keywords=$this->request->get('keywords');
            if($keywords){
                $query->whereRaw("customer.name like '%{$keywords}%' or customer.address like '%{$keywords}%' or customer.contact like '%{$keywords}%'");
            }
        })->limit($offest,15)->order('coupon_list.id desc')->select();
        $this->success('',$list);
    }

    #[Post('recharge')]
    public function recharge()
    {
        $coupon_list_id=$this->request->post('coupon_list_id');
        $type=$this->request->post('type');
        $money=$this->request->post('money');
        Db::startTrans();
        try{
            CardLog::addLog($coupon_list_id,$type,$money,'','服务商管理员后台充值');
            if($type=='add'){
                $couponlist=CouponList::find($coupon_list_id);
                $customer= CustomerModel::find($couponlist->customer_id);
                $user_id=explode(',',$customer->user_id);
                foreach ($user_id as $id){
                    UserLog::addScoreLog($id,'add',$money,'','服务商为会员卡充值赠送积分');
                    break;
                }
            }
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }
}